package com.jy.api.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CopyObjectRequest;
import com.aliyun.oss.model.CopyObjectResult;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

@Slf4j
public class ImageFileOssUtil {


    private static String endpoint = "oss-cn-hangzhou-internal.aliyuncs.com";
    private static String accessKeyId = "LTAI1MFQKaqHdzSw";
    private static String accessKeySecret = "szQyLJryhX4yg0uWccBh3TZUpWAEf2";
    private static String bucketName = "hxypic";
    private static String ADDRESS = "images.huoxingy.com";
    private static OSSClient ossClient;

    private static void init() {
        if (ossClient == null) {
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        }
    }

    public static void imageUpload(InputStream inputStream,
                                   String fileKey) throws FileNotFoundException {
        init();
        if (ossClient != null) {
            ossClient.putObject(bucketName, fileKey, inputStream);

        }
        log.info("image upload isSuccess .......");


    }

    public static String getImageUrl(String fileKey) {
        init();
        if (ossClient != null) {
            Date expiration = new Date(new Date().getTime() + 3600 * 1000);
            URL url = ossClient.generatePresignedUrl(bucketName, fileKey, expiration);
            return url.toString();
        }
        return null;
    }

    /**
     * 拷贝客户端位置
     *
     * @return
     */
    public static void copyClient(String destinationKey) {
        init();
        try {
            // 创建CopyObjectRequest对象
            CopyObjectRequest copyObjectRequest = new CopyObjectRequest(bucketName,
                    "火星捕手客户端.exe", bucketName, destinationKey);
            // 设置新的Metadata
            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentType("application/x-msdownload");
            copyObjectRequest.setNewObjectMetadata(meta);
            // 复制Object
            CopyObjectResult result = ossClient.copyObject(copyObjectRequest);
            System.out.println("ETag: " + result.getETag() + " LastModified: " + result.getLastModified());

        } catch (Exception ex) {
            log.error("拷贝客户端到下载目录失败！");
        }

    }


    public static String getUrl(String fileKey) {
        StringBuffer sb = new StringBuffer();

        sb.append("https://").append(ADDRESS).append("/")
                .append(fileKey);

        return sb.toString();
    }

    /*
    下载OSS文件并压缩到服务器，在执行上传到OSS并且删除服务器文件
     */
    public static void downloadAndUpload(String storeId) throws IOException {
        init();
        //在OSS上拉取文件（源文件）
        OSSObject ossObject = ossClient.getObject(bucketName, "table.zip");

        //输出到目标目录
        File zipFile = Files.createTempFile("", "").toFile();
        ZipOutputStream zipOut = null;
        ZipInputStream inputStream = null;
        try {
            zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
            zipOut.setLevel(ZipOutputStream.STORED);

            inputStream = new ZipInputStream(ossObject.getObjectContent(), Charset.forName("GBK"));
            //COPY source
            while (true) {
                ZipEntry entry = inputStream.getNextEntry();
                if (null == entry) {
                    break;
                }
                zipOut.putNextEntry(new ZipEntry(entry.getName()));
                int temp;
                byte[] bytes = new byte[1024 * 1024];
                while ((temp = inputStream.read(bytes)) != -1) {    // 读取内容
                    zipOut.write(bytes, 0, temp);
                }
                zipOut.closeEntry();
            }
            zipOut.putNextEntry(new ZipEntry("config.ini"));
            zipOut.write(StoreConfigUtil.CALL_CLIENT_CONFIG.getBytes("utf-8"));
            zipOut.closeEntry();
        } catch (IOException e) {
            log.error("Fail to generate zip file for store:{}", storeId, e);
        } finally {
            if (null != inputStream) {
                inputStream.close();
            }
            if (zipOut != null) {
                zipOut.close();
            }
        }
        ossClient.putObject(bucketName, "client/" + storeId + ".zip", zipFile);
        zipFile.delete();
    }


    public static void downloadCallAndClientUpload(String storeId) throws IOException {
        init();
        //在OSS上拉取文件（源文件）
        OSSObject ossObject = ossClient.getObject(bucketName, "callClient.zip");

        //输出到目标目录
        File zipFile = Files.createTempFile("", "").toFile();
        ZipOutputStream zipOut = null;
        ZipInputStream inputStream = null;
        try {
            zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
            zipOut.setLevel(ZipOutputStream.STORED);

            inputStream = new ZipInputStream(ossObject.getObjectContent(), Charset.forName("GBK"));
            //COPY source
            while (true) {
                ZipEntry entry = inputStream.getNextEntry();
                if (null == entry) {
                    break;
                }
                zipOut.putNextEntry(new ZipEntry(entry.getName()));
                int temp;
                byte[] bytes = new byte[1024 * 1024];
                while ((temp = inputStream.read(bytes)) != -1) {    // 读取内容
                    zipOut.write(bytes, 0, temp);
                }
                zipOut.closeEntry();
            }
            zipOut.putNextEntry(new ZipEntry("client.ini"));
            zipOut.write(StoreConfigUtil.CALL_CLIENT_CONFIG.replace("STORE_ID", storeId).getBytes("utf-8"));
            zipOut.closeEntry();
        } catch (IOException e) {
            log.error("Fail to generate zip file for store:{}", storeId, e);
        } finally {
            if (null != inputStream) {
                inputStream.close();
            }
            if (zipOut != null) {
                zipOut.close();
            }
        }
        ossClient.putObject(bucketName, "callClient/" + storeId + ".zip", zipFile);
        zipFile.delete();
    }

    public static void downloadXpCallAndClientUpload(String storeId) throws IOException {
        init();
        //在OSS上拉取文件（源文件）
        OSSObject ossObject = ossClient.getObject(bucketName, "xpService.zip");

        //输出到目标目录
        File zipFile = Files.createTempFile("", "").toFile();
        ZipOutputStream zipOut = null;
        ZipInputStream inputStream = null;
        try {
            zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
            zipOut.setLevel(ZipOutputStream.STORED);

            inputStream = new ZipInputStream(ossObject.getObjectContent(), Charset.forName("GBK"));
            //COPY source
            while (true) {
                ZipEntry entry = inputStream.getNextEntry();
                if (null == entry) {
                    break;
                }
                zipOut.putNextEntry(new ZipEntry(entry.getName()));
                int temp;
                byte[] bytes = new byte[1024 * 1024];
                while ((temp = inputStream.read(bytes)) != -1) {    // 读取内容
                    zipOut.write(bytes, 0, temp);
                }
                zipOut.closeEntry();
            }
            zipOut.putNextEntry(new ZipEntry("clientA.ini"));
            zipOut.write(StoreConfigUtil.CALL_SERVICE_CONFIG.replace("STORE_ID", storeId).getBytes("utf-8"));
            zipOut.closeEntry();
        } catch (IOException e) {
            log.error("Fail to generate zip file for store:{}", storeId, e);
        } finally {
            if (null != inputStream) {
                inputStream.close();
            }
            if (zipOut != null) {
                zipOut.close();
            }
        }
        ossClient.putObject(bucketName, "xpClient/" + storeId + ".zip", zipFile);
        zipFile.delete();
    }


    public static void downloadCallAndServiceUpload(String storeId) throws IOException {
        init();
        //在OSS上拉取文件（源文件）
        OSSObject ossObject = ossClient.getObject(bucketName, "service.zip");

        //输出到目标目录
        File zipFile = Files.createTempFile("", "").toFile();
        ZipOutputStream zipOut = null;
        ZipInputStream inputStream = null;
        try {
            zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
            zipOut.setLevel(ZipOutputStream.STORED);

            inputStream = new ZipInputStream(ossObject.getObjectContent(), Charset.forName("GBK"));
            //COPY source
            while (true) {
                ZipEntry entry = inputStream.getNextEntry();
                if (null == entry) {
                    break;
                }
                zipOut.putNextEntry(new ZipEntry(entry.getName()));
                int temp;
                byte[] bytes = new byte[1024 * 1024];
                while ((temp = inputStream.read(bytes)) != -1) {    // 读取内容
                    zipOut.write(bytes, 0, temp);
                }
                zipOut.closeEntry();
            }
            zipOut.putNextEntry(new ZipEntry("clientA.ini"));
            zipOut.write(StoreConfigUtil.CALL_SERVICE_CONFIG.replace("STORE_ID", storeId).getBytes("utf-8"));
            zipOut.closeEntry();
        } catch (IOException e) {
            log.error("Fail to generate zip file for store:{}", storeId, e);
        } finally {
            if (null != inputStream) {
                inputStream.close();
            }
            if (zipOut != null) {
                zipOut.close();
            }
        }
        ossClient.putObject(bucketName, "service/" + storeId + ".zip", zipFile);
        zipFile.delete();
    }

}













